const exec = require('child_process').execSync;
const execFile = require('child_process').execFileSync;
String.prototype.replaceAll=function(f,e){
	    var reg=new RegExp(f,"g");
	    return this.replace(reg,e); 
}
const appname = 'meblog';
const testContainer = 'meblog_test';
let gitStatusStr =  exec('sh /docker/makeblog/git_status.sh').toString('utf8').trim();
console.log(gitStatusStr);
let gitstatus = gitStatusStr && gitStatusStr.indexOf('200') >= 0 && gitStatusStr.indexOf('OK') >= 0;
console.log(gitstatus);
if(!gitstatus){throw Error('git status is error!');}
let gitEventStr = exec('sh /docker/makeblog/valid_git_do.sh').toString('utf8').trim();
newVersion = gitEventStr.replaceAll('[-T:+]','');
if(!newVersion){
	throw Error('get version is null');
}

let oldVersion = exec("sh /docker/makeblog/get_oldvalue.sh").toString('utf8').trim();

const testProt = 4004;
const prots = [3004,3005]
const holdContainer = {port:4007,name:'meblog_hold'}
let  imagestr = exec('docker images ').toString('utf8').trim();
console.warn('imageslist',imagestr);
let  containerstr = exec('docker ps -a ').toString('utf8').trim();
console.warn('containerlist',containerstr);
console.warn('old',oldVersion,'new',newVersion);
let listMap = (str,flag) =>{
	if(!str){
	 return null;
	}
	let a = str.split('\n');
	if(!a || !a.length){
		return null;
	}
	let iarr =  a.map((it,id)=>{
		  if(id == 0){
		   return null;
		  }
		 //  if(!it || it.indexOf("meblog")<0){ return null; }
		 let arr = it.replace(/\s+/ig,"##").split("##");
   	        let prots =  arr.filter(itx=> itx.indexOf("0.0.0.0:")>=0)
		let port = '';
		// console.log(prots);
		if(prots && prots.length == 1){
                   let tmp_prot = prots[0].match(/0\.0\.0\.0:(\d+)/);
		// console.log(tmp_prot);
                     port = tmp_prot[1]
		}
	        // console.log('port',port);
		 if(flag){
		  arr = arr[1].split(":");
		 }   
		if(arr[0] != appname ){
		 return null;
		}
		return {
                       name:arr[0],
                       tag:arr[1],
			port:port,
                     }
            }).filter(it=>it)
    return iarr;    
}

const imageArr = listMap(imagestr,false);
console.log('images',imageArr);
const allContainerArr  = listMap(containerstr,true );
console.log('allContainers',allContainerArr);
const holdContainerArr = allContainerArr.filter(ix=>ix.port == holdContainer.port);
console.log('holdContainer:',holdContainerArr);
const containerArr = allContainerArr.filter(ix=>ix.port!= holdContainer.port);
console.log('loop container:',containerArr);
const builded = imageArr.filter(it=>it.name ==appname && it.tag ==newVersion);
let needBuild = newVersion != oldVersion || !builded || !builded.length ;
let valid_image_ok = false;

let buildHoldContainer = (imageTag,containerName,prot)=>{
  let startlog = exec(`sh /docker/makeblog/start_hold_container.sh ${imageTag} ${prot} ${containerName}`).toString('utf8').trim();
  return startlog;
}
let buildContainer = (imageTag,containerName,prot)=>{
  let startlog = exec(`sh /docker/makeblog/start_container.sh ${imageTag} ${prot} ${containerName}`).toString('utf8').trim();
  return startlog;
 }
let removeContainer = (containerName) =>{
  return exec(`sh /docker/makeblog/rm_container.sh ${containerName}`).toString('utf8').trim();
}
let toBuildImageTag = `${appname}:${newVersion}`;
if(needBuild){
  console.log("build image");
  let image =  exec(`sh /docker/makeblog/make_image.sh ${appname} ${newVersion}`).toString('utf8').trim();
  console.log('build image log:',image);
  let testimage = buildContainer(toBuildImageTag,testContainer,testProt);
  console.log('test image log:',testimage);
  removeContainer(testContainer);
  valid_image_ok = !! testimage;
 
}

if(needBuild &&  !valid_image_ok){
  throw Error('valid image iserror');
}
if(!holdContainerArr || !holdContainerArr.length || holdContainerArr[0].tag != newVersion || oldVersion != newVersion){
  let buildHoldLog  = buildHoldContainer(toBuildImageTag,holdContainer.name,holdContainer.port);
  console.log('build hold container log:',buildHoldLog);
}
console.log(imageArr);
console.log(containerArr);
console.log('new',newVersion,'old',oldVersion);
if(oldVersion != newVersion){
  exec(`sh /docker/makeblog/wirte_newvalue.sh ${newVersion}`)
}


//  滚动启动
console.log('loop start')
for(let prot of prots){
	let cn = `${appname}_${prot}_${newVersion}`;
  let con = containerArr.filter(c=>c.port == prot )[0]
  console.log('filter continer',con);
   if(con && con.tag == newVersion && con.port == prot){
     // 启动过，就不需要启动了
     continue;
   }
   let oldimagetag = null;
   if(con){
	   console.log('to remove old container',cn);
	  let  cnsp =  con.name.split('_');
	   if(cnsp.length==3){
	    oldimagetag = cnsp[2];
	   }
     let recon = removeContainer(cn);
	  console.log('remove old container log:',recon);
   }
    console.log('to start new container');

    let stcon =  buildContainer(toBuildImageTag,cn,prot);

    console.log('start new  container log:',stcon);
   console.log('wait 2s');
   setTimeout(()=>{
     console.log('wait 2s end !! go ahand');
   },2000)	

}

imageArr.sort((a,b)=>{
   return b.tag.localeCompare(a.tag);
})
console.log('sort images',imageArr);
let imlen = 3;
if(imageArr && imageArr.length>imlen){
   for(let i = 0 ;i<imlen;i++){
	   if(i<imlen){
	     continue;
	   }
       let image = imageArr[i];
       console.log('to remove iamge' ,image);
       let rilog = exec('docker rmi '+image.name+':'+image.tag).toString('utf8').trim();
       console.log('remove image log:',rilog);
   }
}
